package edu.luc.cs413s13.team1.monsterm.remote;

/**
 * Place the initial 8 monsters on the field using
 * the values on the server; processes the JSONArray
 * fetched in doInBackground
 */
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import edu.luc.cs413s13.team1.monsterm.controller.MonstermController;
import edu.luc.cs413s13.team1.monsterm.model.MonstermModel;
import edu.luc.cs413s13.team1.monsterm.model.common.MonsterStateChangeListener;
import edu.luc.cs413s13.team1.monsterm.model.monster.Actor;
import edu.luc.cs413s13.team1.monsterm.model.monster.Monster;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;

public class MonstermRemoteInit extends AsyncTask<URL, Void, JSONArray> {

	private MonstermModel model;
	MonsterStateChangeListener controller;
    private ProgressDialog dialog;
	private HttpGet request;
	
	private JSONArray jsonArray;
	
	public MonstermRemoteInit(MonstermModel model, 
			MonsterStateChangeListener controller) {
		this.model = model;
		this.controller = controller;
		this.dialog = new ProgressDialog((Context)controller);	
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
        this.dialog.setMessage("Please wait");
        this.dialog.show();
	}
	
	@Override
	protected JSONArray doInBackground(final URL... params) {
		
		if (params.length != 1)
			throw new IllegalArgumentException("exactly one argument expected");
		URL url = params[0];
		try {
			final HttpClient client = new DefaultHttpClient();
			request = new HttpGet(url.toURI());
			final HttpResponse response = client.execute(request);
			int status = response.getStatusLine().getStatusCode();
			if (status == 200) {
				//return (JSONArray)response.getEntity().getContent();
				 InputStream is = response.getEntity().getContent();
                 InputStreamReader isr = new InputStreamReader(is);
                 BufferedReader br = new BufferedReader(isr);
                 StringBuilder stringBuffer = new StringBuilder();
                 String line;
                 while ((line=br.readLine()) != null) {
                	 stringBuffer.append(line+"\n");
                 }
                 is.close();
                 isr.close();
                 br.close();
                
                 String result = stringBuffer.toString();
                 return (new JSONArray(result));

			} else if (status == 404) {
				return null;
			}
			else {
				throw new RuntimeException("unexpected server response");
			}
		} catch (final Throwable ex) {
			throw new RuntimeException(ex);
		}
	}

	/**
	 * Connect to the server and get the values in JSONArray
	 */
	@Override
	protected void onPostExecute(final JSONArray result) {
		// Set the progress bar to invisible
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        
		this.jsonArray = result;
		JSONObject jsonObject = null;
		for (int i = 0; i < jsonArray.length(); i++) {
			int x = 0;
			int y = 0;
			try {
				jsonObject = jsonArray.getJSONObject(i);
				x = Integer.parseInt(jsonObject.getString("x"));
				y = Integer.parseInt(jsonObject.getString("y"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
			Actor monster = new Monster();
			((Monster)monster).setMonsterStateChangeListener(controller);
			model.addLivingActor(monster);
		    model.addActor(monster, y, x);
		    
		    // start the initial actors
		    for (Actor a : model.getLivingActors()) {
		    	a.start();
		    }
		}
	}	
}


